var app = getApp();
const apiHost = require('../../../../common/api_host.js');
var utils = require('../../../../utils/utils.js');
var httpJson=require('../../../../utils/http_json.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    commentList:[],
    hasMore:false,
    lz:'<楼主>',
    isfalse:false,
    pageNum:0

  },
  getContent:function(){
    var  url=`${apiHost.config.portalApiHost}/portal/aboveroom/contentDetail/${this.data.id}`;
    
    httpJson.get(url,{},res=>{
      if(res.data.errorCode==0){
        wx.hideLoading()
        res.data.body.time=utils.formatDate2(res.data.body.createdTime)
        this.setData({
         msg:res.data.body

        })
      }
    })
  },
  inputText : function (e) {
    console.log('content的值是===',e.detail.value)
    this.setData({ content: e.detail.value });
  },
  // 点击二,3级评论按钮时触发
  addCom:function(e){
   
    //  发请求时的参数
    console.log(e)
    // 如果不是二级评论就返回
    if(!app.ET(e,'level')){
      return;
    }


    let userId=app.ET(e,'userid');
    let commentId=app.ET(e,'commentid');
    let content=app.ET(e,'content')
    let replyCommentContent=app.ET(e,'replycommentcontent')
    let level=app.ET(e,'level')
    
    let params_er={
      contentId:this.data.id,
      replyUserId:userId,
      replyCommentId:commentId,
      content,
      replyCommentContent,
      level,
      
      // replyCommentContent:this.data.content,
    }

  // 立即显示评论时的参数
    // let index=app.E(e,'idx');
    let commentListIdx=app.EC(e,'idx');
    let beReplyname=app.ET(e,'bereplyname');
    // let commentErMsg={
    //   index,beReplyname
    // }
    this.data.com
    this.setData({
      commenting:true,
      erji:true,
      params_er,
      commentListIdx,
      level,
      beReplyname//为了显示正在回复谁
    })

  },
  // addCom:function(e){
  //   console.log('父亲~~！！@',e)
  // },
  send:function(e){
    var _this=this;
    if(!this.data.content){
      utils.errToast('请输入评论',1000)
      return;
    }
      // 二级评论
    var  url=`${apiHost.config.portalApiHost}/portal/content/addComment`;
    if(this.data.erji){
      this.setData({
        'params_er.replyCommentContent':this.data.content
      })
      
      httpJson.post(url,this.data.params_er,res=>{
      
        if(res.data.errorCode==1){
      
          utils.errToast(res.data.msg,1000)

        }
        if(res.data.errorCode==0){
          utils.successToast("回复成功",500)
          let result=res.data.body
          // }
          let  obj=result;

//来自回复的时候，为了插入数据
          this.data.commentList.forEach((ele,idx)=>{
            if(ele.id==this.data.params_er.replyCommentId){
              this.setData({
                commentListIdx:idx
              })
            }
      
          })
           
          
          if(!this.data.commentList[this.data.commentListIdx].replyCommentList){
            this.data.commentList[this.data.commentListIdx].replyCommentList=[]
          }
            this.data.commentList[this.data.commentListIdx].replyCommentList.unshift(obj)
         this.setData({
          commentList: this.data.commentList,
          content:"",
          erji:false
         })
           
          // 为了实时添加评论，所以要获取到用户信息
         
           
          // obj.user.userName=this.data.userMsg.userName;
          // _this.data.commentList.push(obj)
          // _this.data.commentTotal++
          // _this.setData({
          //   commentList: _this.data.commentList,
          //   sendEnd:true,
          //   content:"",
          //   commentTotal: _this.data.commentTotal
          // })
        }
      })
    }
  
    
    if(!this.data.erji){
      let params={
        contentId:this.data.id,
        content:this.data.content,
        level:1
      }
      let obj={
        content:this.data.content,
        user:{}
      }
      httpJson.post(url,params,res=>{
        if(res.data.errorCode==1){
      
          utils.errToast(res.data.msg,1000)

        }
        if(res.data.errorCode==0){
          utils.successToast("评论成功",1000)
          let result=res.data.body
          let  obj=result;


          _this.data.commentList.unshift(obj)
          _this.data.commentTotal++
          _this.setData({
           commentList: _this.data.commentList,
           content:""
          })


        // var mytime= res.data.body.createdTime
        //   // 为了实时添加评论，所以要获取到用户信息
        //   obj.mytime=utils.formatDate2(mytime);
        //   obj.user.headerImg=this.data.userMsg.headerImg;
        //   obj.user.userName=this.data.userMsg.userName;
        //   _this.data.commentList.unshift(obj)
        //   _this.data.commentTotal++
        //   _this.setData({
        //     commentList: _this.data.commentList,
        //     sendEnd:true,
        //     content:"",
        //     commentTotal: _this.data.commentTotal
        //   })
        }
      })
    }
  },
  addLikeComment:function(e){

    let commentId=app.E(e,"myid");
    let userLike=app.E(e,'islike');
    let index=app.E(e,'idx');
    console.log(commentId,userLike,index)
    var  url;
    if(userLike){
      url =`${apiHost.config.portalApiHost}/portal/content/removeCommentLike`;
      let data={commentId}
      httpJson.post(url,data,res=>{
        if(res.data.errorCode==0){
          var params={};
          var str=`commentList[${index}].userLike`;
          params[str]=false;
         this.setData(params)
         this.data.commentList[index].likeNum--
          this.setData({
            commentList:this.data.commentList
          })
        }
      })
    }
    if(!userLike){
      url =`${apiHost.config.portalApiHost}/portal/content/addCommentLike`;
      let data={commentId}
      httpJson.post(url,data,res=>{
        if(res.data.errorCode==0){
          var params={};
          var str=`commentList[${index}].userLike`;
          params[str]=true;
          this.data.commentList[index].likeNum++
          this.setData({
            commentList:this.data.commentList
          })
         this.setData(params)
        }
      })
    }
   
  

  },
  getCommentList:function(pageNum){
    var  url=`${apiHost.config.portalApiHost}/portal/content/commentList`;
    let params={
      pageNum,
      pageSize:6,
      contentId:this.data.id
    }
    httpJson.get(url,params,res=>{
      if(res.data.errorCode==0){
        setTimeout(()=>{
          wx.hideLoading()
          wx.stopPullDownRefresh()
        },1000)
          /**start1套路代码 */
          if(pageNum==0){
            this.data.commentList=res.data.body.rows
          }
            /**判断是否还有数据 */
          if(res.data.body.totalPage==this.data.pageNum+1){
            this.setData({
              hasMore:false
            })
          }
            /**此时进行分页处理 */
          if(pageNum>0){
            this.data.commentList= this.data.commentList.concat(res.data.body.rows);
          }
          /**end1套路代码 */

        var commentList=res.data.body.rows;
        var replyCommentListLength=0;
        commentList.forEach((ele)=>{
          ele.mytime=utils.formatDate2(ele.createdTime);
          if(ele.replyCommentList.length>3){
            
              ele.newReplyCommentList=ele.replyCommentList.slice(0,3)
              ele.over_three=true
            }
            replyCommentListLength+=ele.replyCommentList.length

        })
       

       
        this.setData({
         commentList: this.data.commentList,
         commentTotal:res.data.body.totalCount,
         replyCommentListLength

        })

      }
    })
  },
  showMore:function(e){
    let index=app.E(e,'idx');
    var params={};
    var str=`commentList[${index}].over_three`;
    params[str]=false;
   
  
    this.setData(params)
  },
  previewImage : function () {
   
    var { msg } = this.data;
  
    wx.previewImage({
      current: msg['img'],
      urls:[msg['img']],
    });
  },
  addLikeContent:function(e){
    let contentId=app.E(e,"myid");
    let userLike=app.E(e,'islike');
  
    var  url;
    if(userLike){
      utils.successToast('取消惊叹成功',500)
      url =`${apiHost.config.portalApiHost}/portal/content/removeLike`;
      let data={contentId}
      httpJson.post(url,data,res=>{
        if(res.data.errorCode==0){
          this.data.msg.likeNum--
          this.setData({
            'msg.userLike':false,
            'msg.likeNum':  this.data.msg.likeNum
          })
        }
      })
    }
    if(!userLike){
      utils.successToast('惊叹成功',500)
      url =`${apiHost.config.portalApiHost}/portal/content/addLike`;
      let data={contentId}
      httpJson.post(url,data,res=>{
        if(res.data.errorCode==0){
          this.data.msg.likeNum++
            this.setData({
              'msg.userLike':true,
              'msg.likeNum':  this.data.msg.likeNum
            })
       
         
      
        
        }
      })
    }
  },
  formSubmit: function(e) {


    var formId = e.detail.formId;
  
    let path = `${apiHost.config.portalApiHost}/portal/userformId/add`;
    httpJson.post(path, { 'formId': formId}, function (data) {
      let res = data.data;
     
    })
   
  },
  // getReplyList:function(pageNum){
  //   var  url=`${apiHost.config.portalApiHost}/portal/content/replyList`;
  //   let params={
  //     pageNum,
  //     pageSize:10,
  //     replyCommentId:this.data.id
  //   }
  //   httpJson.get(url,params,res=>{
  //     if(res.data.errorCode==0){
  //       var commentList=res.data.body.rows;
  //       commentList.forEach((ele)=>{
  //         ele.mytime=utils.formatDate2(ele.createdTime);
  //         if(ele.replyCommentList.length>3){
  //             // ele.newReplyCommentList=ele.replyCommentList.slice(0,3)
  //             // ele.over_three=true
  //         }
  //       })

       
  //       this.setData({
  //        commentList,
  //        commentTotal:res.data.body.totalCount

  //       })

  //     }
  //   })
  // },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('options',options)

    // 房间详情页，或者脑洞详情页
    app.verifyLogin()

    wx.showLoading({
      title: '加载中',
    })
    if(options.nd){
      this.setData({
        fromBrain:true
      })
      wx.setNavigationBarTitle({
        title: '脑洞24H'
      })

    }
    if(!options.nd){
      this.setData({
        fromBrain:false
      })
     
    }
    if(options.id){
      this.setData({
        id:options.id
      })
    }
    //从回复我的那里跳转过来的
    if(options.params){
      console.log(options)
      this.setData({
        commenting:true,
        erji:true,
       
      })
 var params=JSON.parse(options.params);
      
    let replyUserId=params.replyuserid;
    //一级评论的id
    let replyCommentId=params.replycommentid;

   
    let content=params.content
    
    let level=params.level<3?params.level+1:params.level
    let id=params.myid
    
    let params_er={
      //整个内容id
      contentId:id,
      //上一级的用户id
      replyUserId,
      
      //一级评论的id
      replyCommentId,
      
     
      //上一级的内容
      content,
      
      level,
      
     
    }
    this.setData({
      id,
      params_er,
      beReplyname:params.bereplyname
    })
    //静态插入数据
   

   
      console.log('参数',params)

    }
   this. getCommentList(0)
    this.getContent()
    app.getuser(this)


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getCommentList(0)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.commentList.length<this.data.commentTotal){
      this.setData({
        hasMore:true
      })
      
      let pageNum=++this.data.pageNum
      this.getCommentList(pageNum)
    }


  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onShareAppMessage(res) {
    app.share()
    //详情页转发的按钮转发和自带转发是一样的
   
    // if (res.from === 'button') {
      var content=this.data.msg.content;
  
      if(content.length>50){
        content=content.substr(0,50)+'...'
      }
      // 来自页面内转发按钮
      console.log(res.target)
    // }
    return {
      title: content,
     
    }
  }
})